import os
import requests
import random
import time
import json
from datetime import datetime
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 定义目标Ajax接口信息
AJAX_API_URL = "https://crplingxi.com.cn/"  # 替换为实际的Ajax接口URL
# AJAX_API_URL = "https://nginx-uat.crplingxi.com.cn"  # 替换为实际的Ajax接口URL
HEADERS = {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
    'Cookie': 'Hm_lvt_71070c2f506d8f1fe72a10f1ee410006=1713836380,1713857874,1713926208,1714009111; SESSION=169ab982-c55e-4c36-9d36-ae37c28fab66; JSESSIONID=dDcG4WHK_m8MX_Hv-NYkrrxzzfjy-T6gy3zwj6vu; Hm_lpvt_71070c2f506d8f1fe72a10f1ee410006=1714101577',
}
FORM_HEADERS ={
    'Content-Type': 'multipart/form-data',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    'Cookie': 'Hm_lvt_71070c2f506d8f1fe72a10f1ee410006=1713836380,1713857874,1713926208,1714009111; SESSION=169ab982-c55e-4c36-9d36-ae37c28fab66; JSESSIONID=dDcG4WHK_m8MX_Hv-NYkrrxzzfjy-T6gy3zwj6vu; Hm_lpvt_71070c2f506d8f1fe72a10f1ee410006=1714101577',
}

businessTypeOptions = [
    {
        "label": "化工行业",
        "value": "3"
    },
    {
        "label": "机械制造行业",
        "value": "4"
    },
    {
        "label": "冶金行业",
        "value": "8"
    },
    {
        "label": "轻工行业",
        "value": "7"
    },
    {
        "label": "煤炭行业",
        "value": "6"
    },
    {
        "label": "建筑行业",
        "value": "5"
    },
    {
        "label": "公共设施行业",
        "value": "9"
    },
    {
        "label": "备用",
        "value": "99"
    },
    {
        "label": "公共机构",
        "value": "10"
    },
    {
        "label": "商业建筑",
        "value": "11"
    },
    {
        "label": "工业建筑",
        "value": "12"
    },
    {
        "label": "集中供热",
        "value": "13"
    },
    {
        "label": "其他公共设施",
        "value": "14"
    },
    {
        "label": "市政照明",
        "value": "15"
    },
    {
        "label": "集中供暖",
        "value": "16"
    },
    {
        "label": "电力行业",
        "value": "1"
    },
    {
        "label": "电子信息与通信行业",
        "value": "2"
    }
]
def init_from_data():
    projectData = {
            'uids': get_sn(),
            'scene': '',
            'project_name': '',
            'project_address': '',
            'company_name': '',
            'project_price': '',
            'project_time': '',
            'project_text': '',
            'project_detail': '',
            'user_name': '测试用户1',
            'img_url': [],
            'project_file': [],
            'type_state': 2,
            'project_count': 0
        }
    return projectData

def get_sn():
    now = datetime.now()
    s = (
        str(now.year) +
        str(now.month).zfill(2) +
        str(now.day).zfill(2) +
        str(now.hour).zfill(2) +
        str(now.minute).zfill(2) +
        str(now.second).zfill(2) +
        str(now.microsecond // 1000).zfill(3) +
        str(int(random.random() * 1000)).zfill(3)
    )
    return s

def is_file_size_over_10MB(file_path):
    """
    检查指定文件的大小是否超过10MB。

    参数:
        file_path (str): 文件的完整路径。

    返回:
        bool: 如果文件大小超过10MB，则返回True；否则返回False。
    """
    file_size = os.path.getsize(file_path)
    return file_size > 10485760

def getBuessType(name):
    for item in businessTypeOptions:
        if (item['label'] == name):
            return item['value']
    return "999999"

def upload_file(file_path,filename,projectData):
    """上传单个文件到Ajax接口"""

    # 构建文件数据，这里假设接口接受名为`file`的表单项
    formData = {
        'businessType':'projectText',
        'businessId': projectData['uids']
    }
    files = {
        'file': (filename, open(file_path, "rb"),'application/pdf'),
    }
    try:
        response = requests.post(AJAX_API_URL+ '/oss/filemag/upload', data=formData, files=files, headers=HEADERS, verify=False)
        response.raise_for_status()  # 如果响应状态不是2xx，抛出HTTPError异常
        result = json.loads(response.text)
        if result['state'] == "1":
            file_id = result['id']
            print(f"[成功] 成功上传文件 {filename}，响应内容: id:{file_id}")
            datamsg = {
                'uid': uid,
                'name': filename,
                'url': '/oss/filemag/getFileById?fileId=' + file_id
            }
            projectData['project_file'].append(datamsg)
            projectData['img_url'] = projectData['project_file']
            
            # 提交数据
            submit_data(projectData)
        else:
            print(f"[失败] 上传文件失败, msg: {result['msg']} ")
    except requests.exceptions.RequestException as e:
        print(f"[失败] 上传文件 {file_path} 失败，错误信息: {e}")
    finally:
        files["file"][1].close()  # 关闭文件

def submit_data(projectData):
    """提交表格数据接口"""
    # 构建文件数据
    datamsg = {
        'datamsg': json.dumps(projectData)
    }
    
    try:
        response = requests.post(AJAX_API_URL+ '/api/pbmag/dataManage/arithmeticSufferLib/control/addProjectText.do', data=datamsg, headers=HEADERS, verify=False)
        response.raise_for_status()  # 如果响应状态不是2xx，抛出HTTPError异常
        print(f"[成功] 成功提交项目 {projectData['project_name']}，响应内容: {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"[失败] 提交项目 {projectData['project_name']} 失败，错误信息: {e}")

def build_subdirs(folder_path):
    subdirs = []
    for dir in os.listdir(folder_path):
        subdirs.append(dir)
    return subdirs

fileTypeDict = {}
def build_file_type_dict(folder_path):
    # 递归获取目录和子目录中所有文件的列表。
    subdirs = []
    for dir in os.listdir(folder_path):
        subdirs.append(dir)
    for root, dir_names, filenames in os.walk(folder_path):
        # 检查当前目录是否为二级目录
        dirs_in_path =root.split(os.sep)
        # 找出路径中实际包含的指定目录名
        contained_dirs = [dir_name for dir_name in subdirs if dir_name in dirs_in_path]
        if bool(len(contained_dirs)) and len(dirs_in_path) > len(folder_path.split(os.sep)) + 1:
            subdir_name = contained_dirs[0]
            fileTypeDict.update({key: subdir_name for key in filenames})

def upload_files_in_folder(folder_path):
    """读取指定文件夹下所有文件并逐个上传"""
    if not os.path.isdir(folder_path):
        raise NotADirectoryError(f"{folder_path}不是一个有效的目录")

    for root, _, filenames in os.walk(folder_path):
        for filename in filenames:
            file_path = os.path.join(root, filename)
            if is_file_size_over_10MB(file_path):
                print(f"文件 {filename} 大小超过10MB，跳过。")
            else:
                projectData = init_from_data()
                base_name, file_ext = os.path.splitext(filename)
                projectData['project_name'] = base_name
                projectData['project_text'] = base_name
                projectData['project_address'] = base_name

                # 行业类型
                typeValue = getBuessType(fileTypeDict[filename])
                if typeValue == "999999":
                    print(f"[失败] 未知行业类型 文件 {file_path} 跳过")
                else:
                    projectData['business_type'] = typeValue
                    projectData['project_date'] = '2021'
                    upload_file(file_path,filename, projectData) 
                time.sleep(2)

if __name__ == "__main__":
    # login_sys()
    target_folder = r"C:\Users\jacki\Downloads\tempDir\A案例合集\合同能源管理项目案例集（2021-2022）"
    build_file_type_dict(target_folder)
    upload_files_in_folder(target_folder)